<script setup>

import {CircleCheck, Delete, Download, EditPen, Plus, Refresh, Search} from "@element-plus/icons-vue";
import {useStore} from "vuex";
import {computed, onBeforeMount, ref} from 'vue'
import {ElMessage} from "element-plus";
import http from "@/http";
import router from "@/router";

const store = useStore();

const labelPosition = ref('right')

const activeName = ref('first')

const handleClick = (tab, event) => {
  console.log(tab, event)
}
const user = computed(()=> JSON.parse(store.state.user))

const imageUrl = ref(user.value.avatar)

const users = ref({
  userId:user.value.userId,
  nickName:user.value.nickName,
  phonenumber:user.value.phonenumber,
   email:user.value.email,
   oldpwd:user.value.password,
   newpwd:'',
   cfpwd:'',
   sex:user.value.sex
})

const Refuser = ref()

const RefuserPwd = ref()

onBeforeMount(() => {
  console.log(user)
})

const validatePhone = (rule, value, callback) => {
  const reg = /^[1][3-9][0-9]{9}$/;
  if (value == '' || value == undefined || value == null) {
    callback(new Error('请输入手机号'))
  } else {
    if ((!reg.test(value)) && value != '') {
      callback(new Error('请输入正确的电话号码'));
    } else {
      callback();
    }
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== users.value.newpwd) {
    callback(new Error("请输入相同的密码"))
  } else {
    callback()
  }
}

const rules = (
    {
      nickName:[{required:true,message:"昵称不能为空",trigger:'blur'}],
      email:[
             {required:true,message:"邮箱不能为空",trigger:'blur'},
             {type:'email',message: '请输入正确邮箱格式',trigger: 'blur'}
           ],
      phonenumber:[
              {required:true,message:"手机号不能为空",trigger:'blur'},
              {validator:validatePhone,trigger: 'blur'}
           ],
      newpwd:[
              {required:true,message:"请输入新密码",trigger:'blur'}
             ],
      cfpwd:[
              {validator:validatePass2,trigger:'blur'}
             ]
    }
)

const handleAvatarSuccess = (response, uploadFile) => {
  console.log(response)
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  ElMessage({
    message: '上传成功',
    type: 'success',
  })

  user.value.avatar = response.data

  sessionStorage.setItem("user",JSON.stringify(user.value))

  store.commit('getUser',user.value)

}

const  handleAvatarError = ()=>{
  ElMessage({
    type:'error',
    message:'上传失败'
  })
}

const  getTime = (time)=>{
  const date = new Date(time);
  const year = date.getFullYear();
  const month = ('0' + (date.getMonth() + 1)).slice(-2);
  const day = ('0' + date.getDate()).slice(-2);
  const hour = ('0' + date.getHours()).slice(-2);
  const minute = ('0' + date.getMinutes()).slice(-2);
  const second = ('0' + date.getSeconds()).slice(-2);
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

const  aa = () =>{
  store.state.isCollpace = !store.state.isCollpace
}

const UpdloadFile = (file) =>{
  console.log(file)
}

const url = "http://localhost:9988/personnal/Tx?id="+user.value.userId


const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
         BaoCun()
    } else {
      ElMessage({
        type: 'error',
        message: '根据提示完善信息'
      })
    }
  })
}

const submitPwdForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
         UpdPwd()
    } else {
      ElMessage({
        type: 'error',
        message: '根据提示完善信息'
      })
    }
  })
}

const BaoCun = () => {
    http.post("/personnal/UpdGeRzl", users.value).then((res) => {
      if (res.data > 0) {
        ElMessage({
          type: 'success',
          message: res.msg
        })
        user.value.nickName = users.value.nickName
        user.value.phonenumber = users.value.phonenumber
        user.value.email = users.value.email
        user.value.sex = users.value.sex
        sessionStorage.setItem("user",JSON.stringify(user.value))
        store.commit('getUser',user.value)
      } else {
        ElMessage({
          type: 'error',
          message: res.msg
        })
      }
    })
  }

const UpdPwd = ()=>{
  http.post("/personnal/UpdPwd",{password:users.value.newpwd,id:user.value.userId}).then((res)=>{
        if (res.data>0){
           ElMessage({
             type:"success",
             message:res.msg
           })
           loginout()
        }else {
          ElMessage({
            type:'error',
            message:res.msg
          })
        }
  })
}

const loginout = () => {
  sessionStorage.clear()
  router.push('/')
}

</script>

<template>
  <div>
    <!--   导航区   -->
    <div class="Person1" >
      <el-icon size="23" @click="aa"><Fold /></el-icon>
      <div style="display: inline-block;margin-left: 10px;position: absolute;margin-top: 7px">
        <el-icon size="18" color="dodgerblue"><HomeFilled /></el-icon>
      </div>
      <div style="display: inline-block;margin-bottom: 5px;margin-left: 30px;margin-top: 10px">
        <el-breadcrumb separator="/" >
          <el-breadcrumb-item></el-breadcrumb-item>
          <el-breadcrumb-item>   <span style="font-size: 14px;color: black">个人中心</span> </el-breadcrumb-item>
       </el-breadcrumb>
      </div>

    </div>

    <div class="Person2">
       <div style="margin-left: 20px;margin-top: 10px">
           <span style="font-size: 18px">个人信息</span>
       </div>

      <hr style="margin-top: 15px;" color="whitesmoke" >

      <div style="margin-left: 110px;margin-top: 15px">
        <el-upload
            class="avatar-uploader"
            :action=url
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :before-upload="UpdloadFile"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </div>
      <hr style="margin-top: 15px;" color="whitesmoke" >

      <div style="width: 90%;height: 40px;border-bottom: 1px solid gray;margin-left: 15px;margin-top: 10px">
        <div style="margin-top: 7px;display: inline-block">
          <el-text>
            <el-icon color="black"><UserFilled /></el-icon>
             用户名称
          </el-text>
        </div>
        <div style="display:inline-block;margin-left: 170px">
          <el-text class="mx-1">{{user.nickName}}</el-text>
        </div>
      </div>

      <div style="width: 90%;height: 40px;border-bottom: 1px solid gray;margin-left: 15px;margin-top: 10px">
        <div style="margin-top: 7px;display: inline-block">
          <el-text>
            <el-icon><Iphone /></el-icon>
            手机号码
          </el-text>
        </div>
        <div style="display:inline-block;margin-left: 190px;position: relative;top: -20px">
          <el-text class="mx-1">{{user.phonenumber}}</el-text>
        </div>
      </div>

      <div style="width: 90%;height: 40px;border-bottom: 1px solid gray;margin-left: 15px;margin-top: 10px">
        <div style="margin-top: 7px;display: inline-block">
          <el-text>
            <el-icon><Promotion /></el-icon>
            邮箱地址
          </el-text>
        </div>
        <div style="display:inline-block;margin-left: 130px;position: relative;top: -2px">
          <el-text class="mx-1">{{user.email}}</el-text>
        </div>
      </div>

      <div style="width: 90%;height: 40px;border-bottom: 1px solid gray;margin-left: 15px;margin-top: 10px">
        <div style="margin-top: 7px;display: inline-block">
          <el-text>
            <el-icon><Platform /></el-icon>
            所属部门
          </el-text>
        </div>
        <div style="display:inline-block;margin-left: 150px">
          <el-text class="mx-1">{{user.deptId}}</el-text>
        </div>
      </div>

      <div style="width: 90%;height: 40px;border-bottom: 1px solid gray;margin-left: 15px;margin-top: 10px">
        <div style="margin-top: 7px;display: inline-block">
          <el-text>
            <el-icon><Avatar /></el-icon>
            所属角色
          </el-text>
        </div>
        <div style="display:inline-block;margin-left: 170px">
          <el-text class="mx-1">主管</el-text>
        </div>
      </div>

      <div style="width: 90%;height: 40px;border-bottom: 1px solid gray;margin-left: 15px;margin-top: 10px">
        <div style="margin-top: 7px;display: inline-block">
          <el-text>
            <el-icon><Timer /></el-icon>
            创建时间
          </el-text>
        </div>
        <div style="margin-left: 150px;position: relative;top: -20px">
          <el-text class="mx-1">{{getTime(user.createTime)}}</el-text>
        </div>
      </div>
    </div>

    <div class="Person3" >
      <div style="margin-left: 20px;margin-top: 10px">
        <span style="font-size: 18px">基本资料</span>
      </div>
      <hr style="margin-top: 15px">

      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick" style="margin-left: 20px;margin-top: 15px">
        <el-tab-pane label="基本资料" name="first">

          <div style="margin-left: 50px">
            <el-form
                ref="Refuser"
                :label-position="labelPosition"
                label-width="auto"
                :model="users"
                style="max-width: 600px"
                :rules="rules"
            >
              <el-form-item label="用户昵称" prop="nickName" style="margin-top: 20px">
                <el-input v-model="users.nickName" />
              </el-form-item>
              <el-form-item label="电话号码" prop="phonenumber" style="margin-top: 20px">
                <el-input v-model="users.phonenumber" />
              </el-form-item>
              <el-form-item label="邮箱地址" prop="email" style="margin-top: 20px">
                <el-input v-model="users.email" />
              </el-form-item>

              <el-form-item label="性别" prop="sex" style="margin-top: 20px">
                <el-radio-group v-model="users.sex">
                  <el-radio value="0">男</el-radio>
                  <el-radio value="1">女</el-radio>
                </el-radio-group>
              </el-form-item>

              <div style="margin-top: 30px;margin-left: 70px">
                <el-button type="primary" @click="submitForm(Refuser)">保存</el-button>
                <el-button type="danger">关闭</el-button>
              </div>
            </el-form>
          </div>

        </el-tab-pane>
        <el-tab-pane label="修改密码" name="second">
          <div style="margin-left: 50px">
            <el-form
                ref="RefuserPwd"
                :rules="rules"
                :label-position="labelPosition"
                label-width="auto"
                :model="users"
                style="max-width: 600px"
            >
              <el-form-item label="旧密码" style="margin-top: 20px">
                <el-input type="password" disabled v-model="users.oldpwd" />
              </el-form-item>
              <el-form-item label="新密码" prop="newpwd" style="margin-top: 20px">
                <el-input type="password" v-model="users.newpwd" />
              </el-form-item>
              <el-form-item label="重复密码" prop="cfpwd" style="margin-top: 20px">
                <el-input type="password" v-model="users.cfpwd" />
              </el-form-item>
              <div style="margin-top: 30px;margin-left: 70px">
                <el-button type="primary" @click="submitPwdForm(RefuserPwd)">保存</el-button>
                <el-button type="danger">关闭</el-button>
              </div>
            </el-form>
          </div>

        </el-tab-pane>
      </el-tabs>

    </div>

  </div>

</template>


<style scoped lang="scss">
.Person1{
  width: 100%;
  height: 50px;
}
.Person2{
  width: 24%;
  height: 530px;
  background-color: white;
  box-shadow: 0px 0px 5px gray;
  border-radius: 10px;
  display: inline-block;
  margin-left: 80px;
  margin-top: 20px;
}
.Person3{
  width: 60%;
  height: 530px;
  background-color: white;
  box-shadow: 0px 0px 5px gray;
  border-radius: 10px;
  display: inline-block;
  margin-left: 15px;
  position: absolute;
  top: 147px;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width:100px;
  height: 100px;
  text-align: center;
}
</style>